import { io } from 'socket.io-client';

class SocketIO {

    url = '';
    socket = null;

    constructor(url) {
        this.url = url;
    }
    /**
     * 连接socketio
     */
    connect(token) {
        if (!this.socket) {
            this.socket = io(this.url, {
                reconnection: true,
                reconnectionAttempts: 5,
                reconnectionDelay: 1000,
                reconnectionDelayMax: 5000,
                autoConnect: true,
                // transports: ['websocket']
            });
            this.socket.on('reconnect', (attempt) => {
                console.log('socketio重连成功', attempt);
            });
            this.socket.on('connect', () => {
                console.log('socketio连接成功');

                this.socket.emit('login', { token });
            });
            this.socket.on('disconnect', () => {
                console.log('socketio连接断开');
            });
            this.socket.on('connect_error', (error) => {
                console.log('socketio连接错误', error);
            });
        } else {
            console.log('socketio已连接');
        }
    }
    /**
     * 监听事件
     * @param {*} event 
     * @param {*} callback 
     */
    on(event, callback) {
        if (this.socket) {
            this.socket.on(event, callback);
        }else {
            console.log('socketio未连接_on');
        }
    }
    once(event, callback) {
        if (this.socket) {
            this.socket.once(event, callback);
        }else {
            console.log('socketio未连接_emit');
        }
    }
    /**
     * 触发事件
     * @param {*} event 
     * @param {*} data 
     */
    emit(event, data) {
        if (this.socket) {
            this.socket.emit(event, data);
        }else {
            console.log('socketio未连接_emit');
        }
    }
    /**
     * 取消监听事件
     * @param {*} event 
     */
    off(event) {
        if (this.socket) {
            this.socket.off(event);
        }else {
            console.log('socketio未连接_off');
        }
    }
}
const instance = new SocketIO(process.env.VUE_APP_BASE_API);
export {
    instance
}